<template>
	<view class="payment-page">
		<uv-gap height="5" bgColor="transparent" />
		<!-- 收货地址 -->
		<view class="address-section" @click="selectAddress">
			<uv-icon name="map" size="20" color="#ff0000"></uv-icon>
			<view class="address-info">
				<view class="name">{{address.address}}</view>
				<view class="phone">{{address.name}} {{address.tel}}</view>
			</view>
			<uv-icon name="arrow-right" size="16"></uv-icon>
		</view>

		<!-- 商品信息 -->
		<view class="goods-section">
			<view class="time-selector" @click="openPicker">
				<span style="padding-right:10px;">上门时间</span>
				<uv-text :text="model.service_time"></uv-text>
				<uv-icon name="arrow-right" size="16"></uv-icon>
			</view>
			<view class="order-info" v-if="isNight">
				<view class="lbl_info">夜间调度费</view>
				<view class="content_info">￥{{uptick}}</view>
			</view>
		</view>
		<view class="service-card">
			<image :src="pData.image" class="thumb"/>
			<view class="service-info">
				<view class="pName">{{pData.store_name}}</view>
				<view class="spec" v-if="pData.spec">{{pData.spec}}</view>
				<view class="nospec" v-else></view>
				<view class="price">{{pData.price}}</view>
			</view>
			<view style="margin-left:auto; display: flex;">
				<uv-number-box>
					<template v-slot:minus>
						<view class="minus">
							<uv-icon name="minus" color="#333" size="12" @click="decreaseQuantity" />
						</view>
					</template>
					<template v-slot:input>
						<view class="num">
							<uv-text :text="model.num" size="12" color="#333" align="center" />
						</view>
					</template>
					<template v-slot:plus>
						<view class="plus">
							<uv-icon name="plus" color="#333" size="12" @click="increaseQuantity">
							</uv-icon>
						</view>
					</template>
				</uv-number-box>
			</view>
		</view>
		<!-- 备注 -->
		<view class="remark-section">
			<uv-textarea v-model="remark" placeholder="请输入备注" :maxlength="255" />
		</view>

		<!-- 底部结算栏 -->
		<view class="footer-bar">
			<view class="total-price">￥{{model.total_price}}</view>
			<uv-button text="预约并支付" color="rgb(255 0 18)" shape="circle" style="width: 50%;"
				@click="submitOrder"></uv-button>
		</view>
		<uv-popup ref="popTimeRef" mode="bottom" round="10">
			<visitTime :uptick="uptick" @btnClick="selectTime"></visitTime>
		</uv-popup>
		<uv-popup ref="popupRef" mode="bottom" round="10">
			<view class="popup-content">
				<view class="flex align-end justify-center">
					<text class="price1">¥{{model.total_price}}</text>
				</view>
				<uv-gap height="20" bgColor="transparent" />
				<uv-cell-group :border="false">
					<uv-cell v-for="(item, index) in payList" :key="index" :icon="item.piclink" :title="item.pay_name"
						@click="getPayType(index)" :border="false" titleStyle="font-size:28upx">
						<template #value>
							<uv-icon name="checkmark-circle-fill" color="#C52923" size="20"
								v-if="payType == item.type" />
							<uv-icon name="checkmark-circle" color="#B1B1B1" size="20" v-else />
						</template>
					</uv-cell>
				</uv-cell-group>
				<uv-gap height="20" bgColor="transparent" />
				<view class="but">
					<uv-button text="确认付款" color="#C52923" shape="circle" @click="closePopup" />
				</view>
			</view>
		</uv-popup>
		<uv-popup ref="popPwdRef" mode="center" round="10" closeable>
			<view class="popup-content pwd_pop">
				<text class="lbl_pwd">输入密码</text>
				<uv-gap height="20" bgColor="transparent" />
				<view class="flex align-center justify-center padding2">
					<uv-input placeholder="请输入支付密码" type="password" v-model="payPwd" />
				</view>
				<uv-gap height="20" bgColor="transparent" />
				<view class="but">
					<uv-button text="确认支付" color="#C52923" shape="circle" @click="doPay" />
				</view>
			</view>
		</uv-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		onBeforeUnmount
	} from 'vue'
	import dayjs from 'dayjs'
	import {
		aliPay
	} from '@/util/pay.js';
	import {
		openUrl
	} from '@/util/tools.js'
	
	import {
		getDefaultAddress,
		addService,
		getPaymentMethod,
		goPay
	} from '@/api'
	import {
		useOrderStore
	} from '@/store'
	import visitTime from './components/visitTime.vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	// 使用 ref 创建响应式数据
	const orderStore = useOrderStore()
	const orderData = ref(null)
	const popTimeRef = ref(null);
	const uptick = ref('40.00');
	const isNight = ref(false);
	const selectTime = (e, flag) => {
		model.service_time = e;
		isNight.value = flag;
		if (isNight.value) {
			model.total_price = parseFloat(pData.price) * model.num
			model.total_price = (Number(model.total_price) + Number(uptick.value)).toFixed(2)
		} else {
			model.total_price = (parseFloat(pData.price) * model.num).toFixed(2)
		}
		popTimeRef.value.close();
	}
	const remark = ref('');
	const address = ref({
		province: '',
		city: '',
		area: '',
		address: '点击选择收货地址'
	});
	const pData = reactive({
		store_name: '',
		image: '',
		spec: '',
		price: ''
	})
	const model = reactive({
		product_id: '',
		sid: '',
		sku_id: '',
		num: 1,
		address_id: '',
		service_time: '',
		night_price: 0,
		total_price: '',
		remark: ''
	})
	onMounted(() => {
		// 从 Pinia 获取订单数据
		orderData.value = orderStore.orderData
		if (!orderData.value) {
			uni.showToast({
				title: '订单数据不存在',
				icon: 'none'
			})
			uni.navigateBack()
		} else {
			pData.store_name = orderData.value.store_name
			pData.image = orderData.value.image
			pData.price = orderData.value.price
			pData.spec = orderData.value.sku_name
			model.sid = orderData.value.sid
			model.sku_id = orderData.value.sku_id
			model.num = orderData.value.num
			model.total_price = (orderData.value.price * orderData.value.num).toFixed(2)
		}
	})
	onBeforeUnmount(() => {
		// 使用后可以清除数据
		orderStore.clearOrderData()
	})
	const selectAddress = () => {
		uni.navigateTo({
			url: '/pages-user/address?selAddress=1',
			events: {
				// 定义接收事件
				acceptAddress: async (data) => {
					address.value.id = data.id;
					address.value.name = data.name;
					address.value.tel = data.tel;
					address.value.province = data.province;
					address.value.city = data.city;
					address.value.area = data.area;
					address.value.address = data.address;
					model.address_id = data.id;
				}
			},
			success: (res) => {
				// 可选：打印事件通道
				console.log(res.eventChannel)
			}
		})
	};
	// 打开选择器方法
	const openPicker = () => {
		popTimeRef.value.open()
	};
	const payList = ref([])
	const payType = ref('')
	const payPwd = ref('')
	const is_third_party_payment = ref(0)
	const popupRef = ref(null)
	const popPwdRef = ref(null)
	const orderid = ref(0)
	const submitOrder = async () => {
		if (isNight.value) {
			model.night_price = uptick.value
		}
		model.remark = remark.value
		if (!model.service_time) return uni.$uv.toast('请选择上门时间')
		if (payList.value.length == 0) {
			await getPayList()
		}
		if (orderid.value > 0) {
			popupRef.value.open()
		} else {
			orderid.value = (await addService(model)).result
			popupRef.value.open()
		}
	};
	const closePopup = async () => {
		popupRef.value.close()
		if (payType.value) {
			let params = {
				order_id: orderid.value,
				pay_type: payType.value
			}
			if (is_third_party_payment.value == 0) {
				popPwdRef.value.open()
			} else {
				let result = await goPay(params)
				console.log('---pay-----result------',result)
				if (result.code == 200) {
					if(result.result.is_payment_type==2){
						aliPay(result.result.qrData)
					}
					if(result.result.is_payment_type==1){
						openUrl(result.result.qrData)
					}
					
					
					// uni.navigateTo({
					// 	url: '/pages-home/service/pay_result?id=' + orderid.value,
					// })
				} else {
					uni.navigateTo({
						url: '/pages-home/service/pay_result?id=' + orderid.value + '&err=' + result.msg,
					})
				}
			}
		} else {
			uni.showToast({
				title: '请选择支付方式',
				icon: 'none'
			})
		}

	}

	const doPay = async () => {
		if (!payPwd.value) return uni.$uv.toast('请输入支付密码')
		popPwdRef.value.close()
		let params = {
			order_id: orderid.value,
			pay_type: payType.value,
			password: payPwd.value
		}
		let result = await goPay(params)
		if (result.code == 200) {
			uni.navigateTo({
				url: '/pages-home/service/pay_result?id=' + orderid.value,
			})
		} else {
			uni.navigateTo({
				url: '/pages-home/service/pay_result?id=' + orderid.value + '&err=' + result.msg,
			})
		}
	}
	onLoad(async (options) => {
		let res = (await getDefaultAddress()).result
		if (res && res.id>0){
			address.value = res
			model.address_id = address.value.id;
		}
		model.product_id = parseInt(options.id);
	})
	const increaseQuantity = () => {
		model.num++;
		model.total_price = parseFloat(pData.price) * model.num
		if (isNight.value){
			model.total_price = model.total_price + Number(uptick.value)
		}
		model.total_price = model.total_price.toFixed(2)
	};
	const decreaseQuantity = () => {
		if (model.num > 1) {
			model.num--;
			model.total_price = parseFloat(pData.price) * model.num
			if (isNight.value){
				model.total_price = model.total_price + Number(uptick.value)
			}
			model.total_price = model.total_price.toFixed(2)
		}
	};
	const getPayList = async () => {
		const {
			result
		} = await getPaymentMethod()
		payList.value = result
	}
	const getPayType = (index) => {
		payType.value = payList.value[index].type
		is_third_party_payment.value = payList.value[index].is_third_party_payment
	}
</script>

<style lang="scss" scoped>
	.popup-content {
		padding: 30upx 0;

		.but {
			margin: 0 30upx;
		}
		.lbl_pwd {
			font-size: 30upx;
			color: #333;
			text-align: center;
			font-weight: bold;
		}
	}
	
	.pwd_pop{
		width: 600upx;
		text-align: center;
	}

	.padding2 {
		padding: 0 30upx;
	}

	.payment-page {
		background-color: #f7f7f7;
		min-height: 100vh;
		padding-bottom: 80px;
	}

	.status-bar {
		display: flex;
		justify-content: space-between;
		padding: 5px 15px;
		font-size: 12px;
		color: #333;

		.status-icons {
			display: flex;
			gap: 8px;
		}
	}

	.address-section {
		display: flex;
		align-items: center;
		padding: 15px;
		margin: 10px;
		background-color: #fff;
		border-radius: 8px;

		.address-info {
			flex: 1;
			margin-left: 10px;

			.name {
				font-weight: bold;
				margin-bottom: 2px;
			}

			.phone {
				font-size: 12px;
				color: #666;
			}
		}
	}

	.goods-section {
		padding: 15px;
		margin: 10px;
		background-color: #fff;
		border-radius: 8px;
	}

	.time-selector {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 16px;
		background-color: #f7f7f7;
		border-radius: 8px;
	}
	
	.order-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 10px 0;
	
		.lbl_info {
			width: 80px;
			font-size: 24upx;
		}
	
		.content_info {
			flex: 1;
			text-align: right;
			font-size: 24upx;
			color: #ff4d4f;
		}
	}

    .thumb {
		width: 160upx;
		height: 160upx;
		border-radius: 6upx;
		margin-right: 20upx;
		margin-bottom: 20upx;
	}
	.service-card {
		display: flex;
		padding: 15px;
		margin: 10px;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

		.service-image {
			width: 80px;
			height: 80px;
			border-radius: 6px;
			overflow: hidden;
			margin-right: 12px;

			img {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
		}

		.service-info {
			display: flex;
			flex-direction: column;
			height: 80px;

			/* 使容器高度为视口高度 */
			.pName {
				font-size: 28upx;
				font-weight: 600;
				height: 25px;
				line-height: 25px;
			}

			.nospec {
				flex: 1;
			}

			.spec {
				flex: 1;
				background: #f2f2f2;
				padding: 0 5px;
				color: #333;
				line-height: 30px;
				font-size: 22upx;
			}

			.pName,
			.price {
				flex: 0 0 auto;
			}

			.price {
				font-size: 16px;
				color: #ff4d4f;
				font-weight: bold;
				height: 25px;
				line-height: 25px;
			}
		}

		.num {
			width: 60upx;
			margin: 0 10upx;
			padding: 6upx 0;
			background-color: #EBECEE;
		}
	}

	.remark-section {
		margin: 10px;
		background-color: #fff;
		border-radius: 8px;
	}
	
	.price1 {
		font-size:40upx;
		color:#333;
	}

	.footer-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 15px;
		background-color: #fff;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);

		.total-price {
			color: #ff0000;
			font-weight: bold;
			font-size: 16px;
		}

		.submit-btn {
			width: 120px;
			height: 36px;
			background: #ff0000;
			color: #fff;
		}
	}
</style>